<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Java👉网络通信 | 小李博客</title><meta name="keywords" content="JavaSE"><meta name="author" content="小李博客"><meta name="copyright" content="小李博客"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="网络通信相关概念网络(1) 概念：连接终端系统(主机)的通信系统。(2) 功能：实现资源共享、通信。  局域网（Local Area Network，LAN），就是同一区域内通过一定形式连接起来的计算机。 广域网（Wide Area Network，WAN），由LAN延伸到更大的范围。 因特网（Internet），由无数的LAN和WAN组成。 服务器是指提供信息的计算机或程序，客户机是指请求信息的">
<meta property="og:type" content="article">
<meta property="og:title" content="Java👉网络通信">
<meta property="og:url" content="http://xiaoliblog.cn/page/java10.html">
<meta property="og:site_name" content="小李博客">
<meta property="og:description" content="网络通信相关概念网络(1) 概念：连接终端系统(主机)的通信系统。(2) 功能：实现资源共享、通信。  局域网（Local Area Network，LAN），就是同一区域内通过一定形式连接起来的计算机。 广域网（Wide Area Network，WAN），由LAN延伸到更大的范围。 因特网（Internet），由无数的LAN和WAN组成。 服务器是指提供信息的计算机或程序，客户机是指请求信息的">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png">
<meta property="article:published_time" content="2021-01-05T09:58:33.410Z">
<meta property="article:modified_time" content="2021-03-20T10:11:25.446Z">
<meta property="article:author" content="小李博客">
<meta property="article:tag" content="JavaSE">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png"><link rel="canonical" href="http://xiaoliblog.cn/page/java10"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"RTG4CPNBLJ","apiKey":"f1745bdad68ceec57653b78244fe332c","indexName":"MyBlogIndex","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":100,"languages":{"author":"作者: 小李博客","link":"链接: ","source":"来源: 小李博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-center"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-20 18:11:25'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/MyStyle/MyStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="/css/MyStyle/tagStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zykjofficial/zykjresource@master/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/plugins.min.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="小李博客" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小李博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">Java👉网络通信</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-05T09:58:33.410Z" title="发表于 2021-01-05 17:58:33">2021-01-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-03-20T10:11:25.446Z" title="更新于 2021-03-20 18:11:25">2021-03-20</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java%E5%90%8E%E7%AB%AF/">Java后端</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java%E5%90%8E%E7%AB%AF/JavaSE/">JavaSE</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java👉网络通信"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="网络通信"><a href="#网络通信" class="headerlink" title="网络通信"></a>网络通信</h1><h2 id="相关概念"><a href="#相关概念" class="headerlink" title="相关概念"></a>相关概念</h2><p>网络<br>(1) 概念：连接终端系统(主机)的<code>通信系统</code>。<br>(2) 功能：实现<code>资源共享、通信</code>。</p>
<ul>
<li>局域网（Local Area Network，LAN），就是同一区域内通过一定形式连接起来的计算机。</li>
<li>广域网（Wide Area Network，WAN），由LAN延伸到更大的范围。</li>
<li>因特网（Internet），由无数的LAN和WAN组成。</li>
<li><code>服务器</code>是指<code>提供信息的计算机或程序</code>，<code>客户机</code>是指<code>请求信息的计算机或程序</code>，而网络用于连接服务器与客户机，实现两者相互通信。</li>
<li><code>IP地址</code>：IP地址是计算机在互联网中<code>唯一标识</code>。</li>
<li><code>端口</code>：区分<code>应用程序</code>，实现程序间的通信</li>
<li> 假如一台计算机提供了HTTP、FTP等多种服务，那么客户机通过<code>不同的端口</code>来确定连接到服务器的哪项服务上。</li>
</ul>
<blockquote>
<p>说明： 0～1023端口用于知名网络服务和应用，1024以上的端口用于用户的普通应用程序。</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/03/c95323c23793364f9a35a8ef863e6d6c.png"></p>
<h2 id="套接字-Socket"><a href="#套接字-Socket" class="headerlink" title="套接字(Socket)"></a>套接字(Socket)</h2><p>(1)功能：连接<code>应用程序</code>和<code>端口（Port）</code>。<br>(2) 客户端与服务器通过<code>套接字</code>建立<code>连接</code>和<code>通信</code>：<br>① <code>UDP套接字</code>：不可靠。<br>② <code>TCP/IP套接字</code>：</p>
<ul>
<li>可靠的双向流协议；</li>
<li>可发送任意数量的数据；</li>
<li>提供消息确认、错误检测、错误恢复等服务。</li>
</ul>
<blockquote>
<p>Java将套接字抽象化为类，程序设计者只需创建Socket类对象，即可使用套接字。</p>
</blockquote>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/03/3b28b3c6e98b251b01a4ebc87c4356df.png"></p>
<h2 id="C-S模式"><a href="#C-S模式" class="headerlink" title="C/S模式"></a>C/S模式</h2><p>客户端/服务器模式(c/s)<br>①客户端：<code>请求服务</code>的计算机。<br>②服务器：<code>提供服务</code>的计算机。</p>
<ul>
<li>多个客户端可<code>同时访问</code>服务器。</li>
<li> 一台服务器可以<code>同时</code>为数千台客户端<code>服务</code>。</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/03/8377fafe28d6b3224886623096f5a007.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/03/94375e1ff43c101be8a7d9a6dae4f173.png"></p>
<h2 id="java-net包"><a href="#java-net包" class="headerlink" title="java.net包"></a>java.net包</h2><p>(1) <code>InetAddress类</code></p>
<ul>
<li> <code>封装IP地址</code>，提供与IP地址相关的方法。</li>
<li> InetAddress方法会抛出<code>UnknownHostException</code>异常，在主机<code>不存在</code>或网络<code>连接错误</code>时发生。</li>
</ul>
<table>
<thead>
<tr>
<th>InetAddress类常用方法</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><strong>InetAddress</strong> <strong>getLocalHost</strong>( )</td>
<td><strong>创建本地主机的</strong>InetAddress对象（含主机名+IP地址）</td>
</tr>
<tr>
<td><strong>String</strong> <strong>getHostName</strong>( )</td>
<td><strong>如果是</strong>本机则返回计算机名，不是本机则返回主机名，没有域名则是IP地址。</td>
</tr>
<tr>
<td><strong>String</strong> <strong>getHostAddress</strong>( )</td>
<td><strong>返回</strong>IP地址</td>
</tr>
<tr>
<td><strong>InetAddress</strong> <strong>getByName(</strong> <strong>String</strong> <strong>host)</strong></td>
<td><strong>已知主机名，返回主机的<em>InetAddress</em></strong>对象</td>
</tr>
</tbody></table>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> net;</span><br><span class="line"><span class="keyword">import</span> java.net.*;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoaclIPTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">		InetAddress ip;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">//创建本地主机的InetAddress对象(含主机名+IP地址)</span></span><br><span class="line">			ip=InetAddress.getLocalHost();</span><br><span class="line">			String localname=ip.getHostName(); <span class="comment">//获取本机名</span></span><br><span class="line">			String localip=ip.getHostAddress(); <span class="comment">//获取IP地址</span></span><br><span class="line">			<span class="comment">//已知主机名，返回主机的InetAddress对象</span></span><br><span class="line">			<span class="comment">//InetAddress aa=InetAddress.getByName(&quot;SC-201611191816&quot;);</span></span><br><span class="line">			System.out.println(<span class="string">&quot;本机名：&quot;</span> + localname);</span><br><span class="line">		    System.out.println(<span class="string">&quot;本机IP地址：&quot;</span> + localip); </span><br><span class="line">		    System.out.println(<span class="string">&quot;本机InetAddress对象：&quot;</span> + ip);</span><br><span class="line">		  <span class="comment">//  System.out.println(&quot;aa：&quot; + aa);	</span></span><br><span class="line"></span><br><span class="line">		&#125;<span class="keyword">catch</span>(UnknownHostException e) &#123;</span><br><span class="line">			 e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>(2) <code>ServerSocket</code></p>
<ul>
<li>用于创建TCP<code>服务器端</code>Socket，使服务器绑定一个端口，等待客户的连接请求。</li>
</ul>
<table>
<thead>
<tr>
<th>ServerSocket常用方法</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><strong>构造方法：ServerSocket(int port)</strong></td>
<td><strong>创建绑定到特定端口的服务器套接字</strong></td>
</tr>
<tr>
<td><strong>Socket</strong> <strong>accept()</strong></td>
<td><strong>等待</strong>客户端的<strong>连接</strong>，有客户端<strong>连接</strong>会<strong>返回</strong>一个对应的<strong>Socket</strong></td>
</tr>
<tr>
<td><strong>InetAddress getInetAddress()</strong></td>
<td>返回封装了<strong>ServerSocket</strong>绑定的IP地址的<strong>InetAddress对象</strong></td>
</tr>
<tr>
<td><strong>boolean isClosed()</strong></td>
<td>判断<strong>ServerSocket</strong>是否关闭</td>
</tr>
<tr>
<td><strong>void bind(SocketAddress endpoint)</strong></td>
<td>将<strong>ServerSocket对象</strong>绑定到指定的<strong>IP地址和端口号</strong></td>
</tr>
<tr>
<td><strong>int getInetAddress()</strong></td>
<td>返回服务器套接字等待的端口号</td>
</tr>
<tr>
<td><strong>void close()</strong></td>
<td>关闭套接字</td>
</tr>
<tr>
<td><strong>boolean isBound()</strong></td>
<td>判断ServerSocket的绑定状态</td>
</tr>
</tbody></table>
<p>(3) <code>Socket</code></p>
<ul>
<li>创建TCP<strong>客户端</strong>Socket</li>
</ul>
<table>
<thead>
<tr>
<th align="center">Socket常用方法</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><strong>Socket(String hostName,int port)</strong></td>
<td align="center"><strong>根据主机名和端口创建Socket</strong></td>
</tr>
<tr>
<td align="center"><strong>Socket(InetAddress a,int port)</strong></td>
<td align="center"><strong>根据InetAddress和端口创建Socket</strong></td>
</tr>
<tr>
<td align="center"><strong>InputStream getInputStream()</strong></td>
<td align="center"><strong>返回InputStream类型的输入流对象</strong></td>
</tr>
<tr>
<td align="center"><strong>OutputStream getOutputStream()</strong></td>
<td align="center"><strong>返回OutputStream类型的输出流对象</strong></td>
</tr>
<tr>
<td align="center"><strong>int getPort()</strong></td>
<td align="center"><strong>返回Socket对象与服务器端连接端口号</strong></td>
</tr>
<tr>
<td align="center"><strong>InetAddress getLocalAddress()</strong></td>
<td align="center"><strong>获取Socket对象绑定的本地IP地址</strong></td>
</tr>
<tr>
<td align="center"><strong>void close()</strong></td>
<td align="center"><strong>关闭Socket连接，结束本次通信</strong></td>
</tr>
</tbody></table>
<h2 id="编写C-S程序"><a href="#编写C-S程序" class="headerlink" title="编写C/S程序"></a>编写C/S程序</h2><h3 id="服务器端"><a href="#服务器端" class="headerlink" title="服务器端"></a>服务器端</h3><ul>
<li><code>创建</code>一个<code>服务器套接字</code>(ServerSocket)，绑定到指定的<code>端口</code>。</li>
<li>调用<code>accept()</code>方法，<code>侦听</code>来自客户端的<code>请求</code>，如果客户发出请求，则<code>接受</code>连接，<code>返回</code>通信套接字(Socket)。</li>
<li>调用Socket的<code>getInputStream</code>和<code>getOutpuStream</code>方法，获得<code>I/O流</code>，开始网络数据的<code>接收</code>和<code>发送</code>。</li>
<li>关闭<code>通信套接字</code>，关闭<code>服务器套接字</code>。</li>
</ul>
<h3 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h3><ul>
<li><code>创建</code>一个<code>套接字</code>(Socket)，向服务器的侦听端口发出请求。</li>
<li>与服务器正确连接后，调用<code>Socket类</code>的<code>getInputStream()</code>和<code>getOutputStream()</code>方法，获得I/O流，开始网络数据的接收和发送。</li>
<li>关闭<code>通信套接字</code>。<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/03/42e1562d9cc2c9c5022b2a8d710226aa.png"></li>
</ul>
<h3 id="Socket通信方式"><a href="#Socket通信方式" class="headerlink" title="Socket通信方式"></a>Socket通信方式</h3><p>利用Socket方式进行数据通信与传输的整个过程如图所示：<code>Socket</code>对象代表<code>主叫方</code>，<code>ServerSocket</code>对象代表<code>被叫方</code>，执行<code>accept()</code>方法表示<code>同意建立连接</code>。连接一旦建立，会自动创建一个输入流和一个输出流，通过这两个流可以实现数据的发送。<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/03/7c9e2d255aa2b25520f44bf82107f969.png"></p>
<h3 id="Socket编程思路"><a href="#Socket编程思路" class="headerlink" title="Socket编程思路"></a>Socket编程思路</h3><p>(1)<code>I/O流</code></p>
<ul>
<li>计算机系统将除<code>CPU</code>、<code>内存以外</code>的<code>其他设备</code>都当作<code>文件</code>处理，包括网络终端（网卡）也不例外。</li>
<li>两台主机之间通过Socket建立握手连接之后，主要通过<code>I/O流</code>来<code>接收</code>和<code>发送</code>数据，实际上，绝大部分网络操作是在操作<code>I/O流</code>。</li>
<li>操作<code>网络端口流</code>与操作<code>磁盘文件流</code>原理相似。</li>
<li>出于效率的考虑，<code>Socket</code>使用的是<code>字节流</code>，但是在实际操作中，字节往往会带来不便，所以我们一般会把<code>字节流</code>改造成<code>字符流</code>后进行操作。</li>
</ul>
<p>(2)<code>输入</code></p>
<ul>
<li>先利用<code>InputStreamReader</code>将<code>InputStream</code>转化成字符流</li>
<li>然后再使用<code>BufferedReader</code>建立缓冲区，以提高效率。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">InputStream is=socket.getInputStream();</span><br><span class="line">InputStreamReader isr=<span class="keyword">new</span> InputStreamReader(is);</span><br><span class="line">BufferedReader in=<span class="keyword">new</span> BufferedReader(isr);</span><br><span class="line">in.readLine(); <span class="comment">//从流中读出信息</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>(3)<code>输出</code></p>
<ul>
<li>利用<code>PrintWriter</code>类对<code>OutputStream</code>进行包装</li>
<li><code>PrintWriter</code>称为打印输出流，包装类，它可以直接输出各种类型的数据。<br>如：void println( String ) ;<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">OutputStream os=socket.getOutputStream();</span><br><span class="line">PrintWriter pw=<span class="keyword">new</span> PrintWriter(os, <span class="keyword">true</span>);</span><br><span class="line">pw.println(“待写信息”);  <span class="comment">//将信息写入流</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="C-S实例"><a href="#C-S实例" class="headerlink" title="C/S实例"></a>C/S实例</h3><p><code>Client客户端</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> 网络通信;</span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.net.*;</span><br><span class="line"><span class="keyword">import</span> javax.swing.*;</span><br><span class="line"><span class="keyword">import</span> java.awt.*;</span><br><span class="line"><span class="keyword">import</span> java.awt.event.ActionEvent;</span><br><span class="line"><span class="keyword">import</span> java.awt.event.ActionListener;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> <span class="keyword">implements</span> <span class="title">ActionListener</span> </span>&#123;</span><br><span class="line">	JFrame f;</span><br><span class="line">	JPanel p;</span><br><span class="line">	JTextArea jt; <span class="comment">//多行文本域</span></span><br><span class="line">	JTextField t;  <span class="comment">//单行文本域</span></span><br><span class="line">	JButton b;</span><br><span class="line">	JScrollPane jsp;<span class="comment">//滚动条</span></span><br><span class="line">	PrintWriter pw; <span class="comment">//防止局部变量</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Client</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		f=<span class="keyword">new</span> JFrame(<span class="string">&quot;客户端窗口&quot;</span>);</span><br><span class="line">		p=<span class="keyword">new</span> JPanel();</span><br><span class="line">		jt=<span class="keyword">new</span> JTextArea();</span><br><span class="line">		t=<span class="keyword">new</span> JTextField(<span class="number">20</span>);</span><br><span class="line">		b=<span class="keyword">new</span> JButton(<span class="string">&quot;发送&quot;</span>);</span><br><span class="line">		b.addActionListener(<span class="keyword">this</span>);</span><br><span class="line">		f.add(p);</span><br><span class="line">		p.add(jt);</span><br><span class="line">		p.add(t);</span><br><span class="line">		p.add(b);</span><br><span class="line">		jsp=<span class="keyword">new</span> JScrollPane(jt); <span class="comment">//文本域加滚动条</span></span><br><span class="line">		f.add(jsp);</span><br><span class="line">		f.setSize(<span class="number">350</span>,<span class="number">250</span>);</span><br><span class="line">		f.setLocation(<span class="number">300</span>, <span class="number">200</span>);</span><br><span class="line">		f.add(p,BorderLayout.SOUTH);</span><br><span class="line">		f.setIconImage((<span class="keyword">new</span> ImageIcon(<span class="string">&quot;MyImage/qq图标.jpg&quot;</span>)).getImage());</span><br><span class="line">		f.setResizable(<span class="keyword">false</span>);</span><br><span class="line">		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</span><br><span class="line">		<span class="comment">/*System.exit(0)是退出整个程序，如果有多个窗口，全部都销毁退出。</span></span><br><span class="line"><span class="comment">frame.setDefaultCloseOperation()是设置用户在此窗体上发起&quot;close&quot;时默认执行的操作。必须指定以下选项之一： </span></span><br><span class="line"><span class="comment">  (1)DO_NOTHING_ON_CLOSE（在WindowConstants中定义）：不执行任何操作，要求程序在已注册的 WindowListener 对象的 windowClosing 方法中处理该操作。 </span></span><br><span class="line"><span class="comment">  (2)HIDE_ON_CLOSE（在WindowConstants中定义）：调用任意已注册的WindowListener对象后自动隐藏该窗体。 </span></span><br><span class="line"><span class="comment">  (3)DISPOSE_ON_CLOSE（在WindowConstants中定义）：调用任意已注册WindowListener的对象后自动隐藏并释放该窗体。 </span></span><br><span class="line"><span class="comment">  (4)EXIT_ON_CLOSE（在JFrame中定义）：使用System exit方法退出应用程序。仅在应用程序中使用。 </span></span><br><span class="line"><span class="comment">默认情况下，该值被设置为 HIDE_ON_CLOSE</span></span><br><span class="line"><span class="comment">也就是说没有设置的话,默认点关闭时只是隐藏窗体,在后台进程中还可以看到，如果有多个窗口，只是销毁调用dispose的窗口，其他窗口仍然存在，整个应用程序还是处于运行状态。*/</span></span><br><span class="line">		f.setVisible(<span class="keyword">true</span>);</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//客户端程序思路</span></span><br><span class="line">		<span class="comment">//创建一个套接字(Socket)，向服务器的侦听端口发出请求。</span></span><br><span class="line">		<span class="comment">//与服务器正确连接后，调用Socket类的getInputStream()（接受）和getOutputStream()（发送）方法，获得I/O流，开始网络数据的接收和发送。</span></span><br><span class="line">		<span class="comment">//关闭通信套接字。</span></span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			Socket s=<span class="keyword">new</span> Socket(<span class="string">&quot;127.0.0.1&quot;</span>,<span class="number">8998</span>); <span class="comment">//进入端口，参数为服务器IP地址和端口 可通过cmd命令查找 ping和netstat -an </span></span><br><span class="line">			<span class="comment">//尝试建立与服务器的连接。如果成功，则返回Socket对象。</span></span><br><span class="line">			</span><br><span class="line">			<span class="comment">//向服务器发送信息</span></span><br><span class="line">			 pw=<span class="keyword">new</span> PrintWriter(s.getOutputStream(),<span class="keyword">true</span>);</span><br><span class="line">			</span><br><span class="line">			</span><br><span class="line">			<span class="comment">//读取键盘控制台的内容</span></span><br><span class="line">			InputStreamReader isr=<span class="keyword">new</span> InputStreamReader(System.in);</span><br><span class="line">			BufferedReader br=<span class="keyword">new</span> BufferedReader(isr);</span><br><span class="line">			</span><br><span class="line">			<span class="comment">//接收服务器的内容</span></span><br><span class="line">			InputStreamReader isr1=<span class="keyword">new</span> InputStreamReader(s.getInputStream());</span><br><span class="line">			BufferedReader br1=<span class="keyword">new</span> BufferedReader(isr1);</span><br><span class="line">			</span><br><span class="line">			<span class="comment">//死循环 多次交流</span></span><br><span class="line">			<span class="keyword">while</span>(<span class="keyword">true</span>) &#123;</span><br><span class="line">				<span class="comment">/*System.out.println(&quot;客户端说:&quot;);</span></span><br><span class="line"><span class="comment">				String str=br.readLine(); //接受控制台</span></span><br><span class="line"><span class="comment">				pw.println(str);//向服务器发送信息</span></span><br><span class="line"><span class="comment">				*/</span></span><br><span class="line">				</span><br><span class="line">				String str1=br1.readLine();<span class="comment">//接受服务器的信息</span></span><br><span class="line">				jt.append(<span class="string">&quot;服务器对我说说:&quot;</span>+str1+<span class="string">&quot;\r\n&quot;</span>);  <span class="comment">//在多行文本域显示</span></span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="comment">//s.close();//关闭头接字流</span></span><br><span class="line">		&#125;<span class="keyword">catch</span>(Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// TODO 自动生成的方法存根</span></span><br><span class="line">		Client c=<span class="keyword">new</span> Client();</span><br><span class="line">		<span class="keyword">new</span> Client();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">actionPerformed</span><span class="params">(ActionEvent e)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// TODO 自动生成的方法存根</span></span><br><span class="line">		<span class="keyword">if</span>(e.getSource()==b) &#123;</span><br><span class="line">			String str=t.getText();</span><br><span class="line">			jt.append(<span class="string">&quot;我对服务器说:&quot;</span>+str+<span class="string">&quot;\r\n&quot;</span>);  <span class="comment">//append追加  不覆盖前面的内容</span></span><br><span class="line">			<span class="comment">//setText与append区别 在于不会覆盖之前的信息</span></span><br><span class="line">			pw.println(str);<span class="comment">//发送给客户端</span></span><br><span class="line">			t.setText(<span class="string">&quot;&quot;</span>);<span class="comment">//每次发完单行文本框清空</span></span><br><span class="line">		&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<p><code>Server服务端</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> 网络通信;</span><br><span class="line"><span class="keyword">import</span> java.net.*;</span><br><span class="line"><span class="keyword">import</span> java.awt.*;</span><br><span class="line"><span class="keyword">import</span> java.awt.event.ActionEvent;</span><br><span class="line"><span class="keyword">import</span> java.awt.event.ActionListener;</span><br><span class="line"><span class="comment">//尝试写好窗口 继承实现</span></span><br><span class="line"><span class="keyword">import</span> javax.swing.*;</span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Server</span> <span class="keyword">implements</span> <span class="title">ActionListener</span> </span>&#123;</span><br><span class="line">	JFrame f;</span><br><span class="line">	JPanel p;</span><br><span class="line">	JTextArea jt; <span class="comment">//多行文本域</span></span><br><span class="line">	JTextField t;  <span class="comment">//单行</span></span><br><span class="line">	JButton b;</span><br><span class="line">	JScrollPane jsp;<span class="comment">//滚动条</span></span><br><span class="line">	PrintWriter pw;  <span class="comment">//消除局部变量</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Server</span><span class="params">()</span></span>&#123;</span><br><span class="line">		f=<span class="keyword">new</span> JFrame(<span class="string">&quot;服务器窗口&quot;</span>);</span><br><span class="line">		p=<span class="keyword">new</span> JPanel();</span><br><span class="line">		jt=<span class="keyword">new</span> JTextArea();</span><br><span class="line">		t=<span class="keyword">new</span> JTextField(<span class="number">20</span>);</span><br><span class="line">		b=<span class="keyword">new</span> JButton(<span class="string">&quot;发送&quot;</span>);</span><br><span class="line">		b.addActionListener(<span class="keyword">this</span>);</span><br><span class="line">		f.add(p);</span><br><span class="line">		</span><br><span class="line">		p.add(jt);</span><br><span class="line">		p.add(t);</span><br><span class="line">		p.add(b);</span><br><span class="line">		jsp=<span class="keyword">new</span> JScrollPane(jt); <span class="comment">//文本域加滚动条</span></span><br><span class="line">		f.add(jsp);</span><br><span class="line">		f.setSize(<span class="number">350</span>,<span class="number">250</span>);</span><br><span class="line">		f.setLocation(<span class="number">300</span>, <span class="number">600</span>);</span><br><span class="line">		f.add(p,BorderLayout.SOUTH);</span><br><span class="line">		f.setIconImage(<span class="keyword">new</span> ImageIcon(<span class="string">&quot;MyImage/qq图标.jpg&quot;</span>).getImage());</span><br><span class="line">		f.setResizable(<span class="keyword">false</span>);</span><br><span class="line">		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</span><br><span class="line">		<span class="comment">/*System.exit(0)是退出整个程序，如果有多个窗口，全部都销毁退出。</span></span><br><span class="line"><span class="comment">frame.setDefaultCloseOperation()是设置用户在此窗体上发起&quot;close&quot;时默认执行的操作。必须指定以下选项之一： </span></span><br><span class="line"><span class="comment">  (1)DO_NOTHING_ON_CLOSE（在WindowConstants中定义）：不执行任何操作，要求程序在已注册的 WindowListener 对象的 windowClosing 方法中处理该操作。 </span></span><br><span class="line"><span class="comment">  (2)HIDE_ON_CLOSE（在WindowConstants中定义）：调用任意已注册的WindowListener对象后自动隐藏该窗体。 </span></span><br><span class="line"><span class="comment">  (3)DISPOSE_ON_CLOSE（在WindowConstants中定义）：调用任意已注册WindowListener的对象后自动隐藏并释放该窗体。 </span></span><br><span class="line"><span class="comment">  (4)EXIT_ON_CLOSE（在JFrame中定义）：使用System exit方法退出应用程序。仅在应用程序中使用。 </span></span><br><span class="line"><span class="comment">默认情况下，该值被设置为 HIDE_ON_CLOSE</span></span><br><span class="line"><span class="comment">也就是说没有设置的话,默认点关闭时只是隐藏窗体,在后台进程中还可以看到，如果有多个窗口，只是销毁调用dispose的窗口，其他窗口仍然存在，整个应用程序还是处于运行状态。*/</span></span><br><span class="line">		f.setVisible(<span class="keyword">true</span>);</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		<span class="comment">/*  查找IP地址方法</span></span><br><span class="line"><span class="comment">		InetAddress ip;</span></span><br><span class="line"><span class="comment">		try &#123;</span></span><br><span class="line"><span class="comment">			ip = InetAddress.getLocalHost();</span></span><br><span class="line"><span class="comment">			 //创建本地主机的InetAddress对象(含主机名+IP地址)	   </span></span><br><span class="line"><span class="comment">			String localname = ip.getHostName(); 	// 获取本机名</span></span><br><span class="line"><span class="comment">	  String localip = ip.getHostAddress();	 // 获取IP地址</span></span><br><span class="line"><span class="comment">	  InetAddress  aa=  InetAddress.getByName(&quot;SC-201611191816&quot;);</span></span><br><span class="line"><span class="comment">		//已知主机名，返回主机的InetAddress对象</span></span><br><span class="line"><span class="comment">	  System.out.println(&quot;本机名：&quot; + localname);</span></span><br><span class="line"><span class="comment">	  System.out.println(&quot;本机IP地址：&quot; + localip); </span></span><br><span class="line"><span class="comment">	  System.out.println(&quot;本机InetAddress对象：&quot; + ip);</span></span><br><span class="line"><span class="comment">	  System.out.println(&quot;aa：&quot; + aa);	</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">		&#125; catch (UnknownHostException e1) &#123;</span></span><br><span class="line"><span class="comment">			// TODO 自动生成的 catch 块</span></span><br><span class="line"><span class="comment">			e1.printStackTrace();</span></span><br><span class="line"><span class="comment">		&#125; </span></span><br><span class="line"><span class="comment">       </span></span><br><span class="line"><span class="comment">		*/</span></span><br><span class="line">		<span class="comment">//服务端程序思路</span></span><br><span class="line">		<span class="comment">//创建一个服务器套接字(ServerSocket)，绑定到指定的端口。</span></span><br><span class="line">		<span class="comment">//调用accept()方法，侦听来自客户端的请求，如果客户发出请求，则接受连接，返回通信套接字(Socket)。</span></span><br><span class="line">		<span class="comment">//InputStreamReader getInputStream BufferedReader 读取客户端和控制台</span></span><br><span class="line">		<span class="comment">//调用Socket的getInputStream（读取）和getOutpuStream（发送）方法，获得I/O流，开始网络数据的接收和发送</span></span><br><span class="line">		<span class="comment">//PrintWriter  getOutputStream方法发送</span></span><br><span class="line">		<span class="comment">//关闭通信套接字，关闭服务器套接字。</span></span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">		ServerSocket ss=<span class="keyword">new</span> ServerSocket(<span class="number">8998</span>);</span><br><span class="line">		<span class="comment">//ServerSocket在服务器上定义一个接口  方便客户端连接</span></span><br><span class="line">		System.out.println(<span class="string">&quot;服务器正在监听&quot;</span>);</span><br><span class="line">		Socket so=ss.accept();</span><br><span class="line">		<span class="comment">//等待客户机的链接，若链接，则创建一个Socket类型的套接字</span></span><br><span class="line">		<span class="comment">//套接字：连接应用程序和端口 客户端与服务器通过套接字建立连接和通信</span></span><br><span class="line">		</span><br><span class="line">		<span class="comment">//读取客户端发来的信息</span></span><br><span class="line">		<span class="comment">//先利用InputStreamReader将InputStream转化成字符流。</span></span><br><span class="line">		<span class="comment">//然后再使用BufferedReader建立缓冲区，以提高效率。</span></span><br><span class="line">		<span class="comment">//readLine()方法读取</span></span><br><span class="line">		InputStreamReader isr=<span class="keyword">new</span> InputStreamReader(so.getInputStream());</span><br><span class="line">		BufferedReader br=<span class="keyword">new</span> BufferedReader(isr);</span><br><span class="line">	</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//给客户端发信息</span></span><br><span class="line">		<span class="comment">//利用PrintWriter类对OutputStream进行包装</span></span><br><span class="line">		<span class="comment">//PrintWriter称为打印输出流，包装类，它可以直接输出各种类型的数据。</span></span><br><span class="line">		<span class="comment">//如：void println( String ) ;</span></span><br><span class="line">         pw = <span class="keyword">new</span> PrintWriter(so.getOutputStream(),<span class="keyword">true</span>);</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//读取服务器控制台发来的信息</span></span><br><span class="line">		<span class="comment">/*</span></span><br><span class="line"><span class="comment">         InputStreamReader isr1=new InputStreamReader(System.in);</span></span><br><span class="line"><span class="comment">		BufferedReader br1=new BufferedReader(isr1);</span></span><br><span class="line"><span class="comment">		*/</span></span><br><span class="line">		<span class="keyword">while</span>(<span class="keyword">true</span>) &#123;</span><br><span class="line">			String str=br.readLine();  <span class="comment">//接受客户端的信息</span></span><br><span class="line">			jt.append(<span class="string">&quot;客户端对我说说:&quot;</span>+str+<span class="string">&quot;\r\n&quot;</span>);  <span class="comment">//在多行文本域显示</span></span><br><span class="line">			<span class="comment">/*System.out.println(&quot;服务器说:&quot;);</span></span><br><span class="line"><span class="comment">			String str1=br1.readLine();</span></span><br><span class="line"><span class="comment">			pw.println(str1);   //输出服务器发送的信息  */</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//so.close();//关闭套接字流    结束点红点 再点双叉防止下次运行 端口被占用</span></span><br><span class="line">		&#125;<span class="keyword">catch</span>(Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// TODO 自动生成的方法存根</span></span><br><span class="line">		Server s=<span class="keyword">new</span> Server();</span><br><span class="line">		<span class="keyword">new</span> Server();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">//监听</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">actionPerformed</span><span class="params">(ActionEvent e)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// TODO 自动生成的方法存根</span></span><br><span class="line">		<span class="keyword">if</span>(e.getSource()==b) &#123;  <span class="comment">//是否点击按钮发送</span></span><br><span class="line">			String str=t.getText();   <span class="comment">//从单行文本域中取出1来</span></span><br><span class="line">			jt.append(<span class="string">&quot;我对客户端说:&quot;</span>+str+<span class="string">&quot;\r\n&quot;</span>);  <span class="comment">//append追加  不覆盖前面的内容  发送到多行文本域</span></span><br><span class="line">			<span class="comment">//setText与append区别 在于不会覆盖之前的信息</span></span><br><span class="line">			pw.println(str); <span class="comment">//发送给客户端</span></span><br><span class="line">			t.setText(<span class="string">&quot;&quot;</span>); <span class="comment">//每次发完单行文本框清空</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/03/bf4f1d6a414f9a4ddf2f0e62b0234107.png"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">小李博客</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://xiaoliblog.cn">https://xiaoliblog.cn</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://xiaoliblog.cn" target="_blank">小李博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaSE/">JavaSE</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src="/img/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.png" target="_blank"><img class="post-qr-code-img" src="/img/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/page/java09.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java👉事件处理</div></div></a></div><div class="next-post pull-right"><a href="/page/java01.html"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java👉IO流</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/page/java01.html" title="Java👉IO流"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-05</div><div class="title">Java👉IO流</div></div></a></div><div><a href="/page/java06.html" title="Java👉泛型和枚举"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-05</div><div class="title">Java👉泛型和枚举</div></div></a></div><div><a href="/page/java12.html" title="Java👉异常机制"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-05</div><div class="title">Java👉异常机制</div></div></a></div><div><a href="/page/java03.html" title="Java👉JDBC"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-05</div><div class="title">Java👉JDBC</div></div></a></div><div><a href="/page/java09.html" title="Java👉事件处理"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-05</div><div class="title">Java👉事件处理</div></div></a></div><div><a href="/page/java11.html" title="Java👉线程、线程通信"><img class="cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/30/0b4418a37c4d8fd66e1607c74793c6be.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-05</div><div class="title">Java👉线程、线程通信</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">小李博客</div><div class="author-info__description">越努力，越幸运！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xiaoliblog"><i class="fab fa-github"></i><span>博主的GitHub首页</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/xiaoliblog" target="_blank" title="Gitee"><i class="iconfont icon-gitee card_icon_gitee"></i></a><a class="social-icon" href="https://space.bilibili.com/390969485" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili card_icon_bilibili"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2312057536&amp;site=CSDN&amp;menu=yes" target="_blank" title="QQ"><i class="iconfont icon-qq card_icon_qq"></i></a><a class="social-icon" href="https://github.com/xiaoliblog" target="_blank" title="GitHub"><i class="iconfont icon-git card_icon_git"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_43266250?spm=1010.2135.3001.5113" target="_blank" title="CSDN"><i class="iconfont icon-csdn card_icon_csdn"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">正在考研备考中💦</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1"><span class="toc-number">1.</span> <span class="toc-text">网络通信</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E6%A6%82%E5%BF%B5"><span class="toc-number">1.1.</span> <span class="toc-text">相关概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A5%97%E6%8E%A5%E5%AD%97-Socket"><span class="toc-number">1.2.</span> <span class="toc-text">套接字(Socket)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#C-S%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.3.</span> <span class="toc-text">C&#x2F;S模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#java-net%E5%8C%85"><span class="toc-number">1.4.</span> <span class="toc-text">java.net包</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%96%E5%86%99C-S%E7%A8%8B%E5%BA%8F"><span class="toc-number">1.5.</span> <span class="toc-text">编写C&#x2F;S程序</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF"><span class="toc-number">1.5.1.</span> <span class="toc-text">服务器端</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="toc-number">1.5.2.</span> <span class="toc-text">客户端</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Socket%E9%80%9A%E4%BF%A1%E6%96%B9%E5%BC%8F"><span class="toc-number">1.5.3.</span> <span class="toc-text">Socket通信方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Socket%E7%BC%96%E7%A8%8B%E6%80%9D%E8%B7%AF"><span class="toc-number">1.5.4.</span> <span class="toc-text">Socket编程思路</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#C-S%E5%AE%9E%E4%BE%8B"><span class="toc-number">1.5.5.</span> <span class="toc-text">C&#x2F;S实例</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/page/project01.html" title="前端实例🥳响应式网站首页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c19917500ab083c77c7613263ba7ee74d5a08ae6/2021/04/30/469f30b141d73fa0fc4c962662d5813f.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="前端实例🥳响应式网站首页"/></a><div class="content"><a class="title" href="/page/project01.html" title="前端实例🥳响应式网站首页">前端实例🥳响应式网站首页</a><time datetime="2021-04-30T11:50:53.094Z" title="发表于 2021-04-30 19:50:53">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/WeChatpay.html" title="微信支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@f2f670b92ea149650ffa7834354fc90284f2f44a/2021/04/29/5bdc9b381a06193d27cf2fb7c2fb608a.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="微信支付对接"/></a><div class="content"><a class="title" href="/page/WeChatpay.html" title="微信支付对接">微信支付对接</a><time datetime="2021-04-29T12:20:48.070Z" title="发表于 2021-04-29 20:20:48">2021-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Alipay.html" title="支付宝支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61a9b6a6e09e4bda38bb08e3104b717885beaee5/2021/04/29/c3fa51f9cf14e90d9e5a7aa8814dd041.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="支付宝支付对接"/></a><div class="content"><a class="title" href="/page/Alipay.html" title="支付宝支付对接">支付宝支付对接</a><time datetime="2021-04-27T16:00:00.000Z" title="发表于 2021-04-28 00:00:00">2021-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Pagination+PageHelper实现分页"/></a><div class="content"><a class="title" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页">Vue.js前端框架🎯Pagination+PageHelper实现分页</a><time datetime="2021-04-26T14:48:39.701Z" title="发表于 2021-04-26 22:48:39">2021-04-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Vue-Element-admin模版"/></a><div class="content"><a class="title" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版">Vue.js前端框架🎯Vue-Element-admin模版</a><time datetime="2021-04-19T16:00:00.000Z" title="发表于 2021-04-20 00:00:00">2021-04-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By 小李博客</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">🎯Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">🎉Butterfly</a></div><div class="footer_custom_text"><span><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a><a style="margin-inline:5px" target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vercel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a><a style="margin-inline:5px" target="_blank" href="https://coding.net/ "><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a><a style="margin-inline:5px" target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a><a style="margin-inline:5px" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></span></div><div class="icp"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="/img/icp.png" alt="ICP"/><span>湘ICP备2021002541号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script><script src="/js/main.js"></script><script defer src="/js/tw_cn.js"></script><script defer src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script defer src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script defer src="/js/search/algolia.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1.3.0/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script defer src="//lib.baomitu.com/jquery/3.5.1/jquery.min.js"></script><script defer src="https://myhkw.cn/api/player/160561664166" id="myhk" key="160561664166" m="1"></script><div><canvas id="snow" style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none"></canvas></div><script>const notMobile = (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)));</script><scrip async type="text/javascript" src="https://cdn.jsdelivr.net/gh/Candinya/Kratos-Rebirth@latest/source/js/snow.min.js"></scrip><scrip defer src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></scrip><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script>var gitcalendar = new Vue({
  el: '#gitcalendar',
  data: {
    simplemode: true, 
    user: 'xiaoliblog',
    fixed: 'fixed',
    px: 'px',
    x: '',
    y: '',
    span1: '',
    span2: '',
    month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthchange: [],
    oneyearbeforeday: '',
    thisday: '',
    amonthago: '',
    aweekago: '',
    weekdatacore: 0,
    datacore: 0,
    total: 0,
    datadate: '',
    data: [],
    positionplusdata: [],
    firstweek: [],
    lastweek: [],
    beforeweek: [],
    thisweekdatacore: 0,
    mounthbeforeday: 0,
    mounthfirstindex: 0,
    crispedges: 'crispedges',
    thisdayindex: 0,
    amonthagoindex: 0,
    amonthagoweek: [],
    firstdate: [],
    first2date: [],
    montharrbefore: [],
    monthindex: 0,
    color: ['#ebedf0', '#f1f8ff', '#dbedff', '#c8e1ff', '#79b8ff', '#2188ff', '#0366d6', '#005cc5', '#044289', '#032f62', '#05264c']
  },
  methods: {
    selectStyle(data, event) {
      document.querySelector('.angle-wrapper').style.display = 'block'
      this.span1 = data.date;
      this.span2 = data.count;
      this.x = event.clientX - 100;
      this.y = event.clientY - 60
    },
    outStyle() {
      document.querySelector('.angle-wrapper').style.display = 'none'
    },
    thiscolor(x) {
      if (x === 0) {
        let i = parseInt(x / 2);
        return this.color[0]
      } else if (x < 2) {
        return this.color[1]
      } else if (x < 20) {
        let i = parseInt(x / 2);
        return this.color[i]
      } else {
        return this.color[9]
      }
    },
  }
});
var apiurl = 'python-github-calendar-api-ruby.vercel.app' ? 'https://python-github-calendar-api-ruby.vercel.app/api?' : 'https://githubapi.ryanchristian.dev/user/'
var githubapiurl = apiurl + gitcalendar.user;
//canvas绘图
function responsiveChart() {
  let c = document.getElementById("gitcanvas");
  if (c) {
    let cmessage = document.getElementById("gitmessage");
    let ctx = c.getContext("2d");
    c.width = document.getElementById("gitcalendarcanvasbox").offsetWidth;
    let linemaxwitdh = 0.96 * c.width / gitcalendar.data.length;
    c.height = 9 * linemaxwitdh;
    let lineminwitdh = 0.8 * linemaxwitdh;
    let setposition = {
      x: 0.02 * c.width,
      y: 0.025 * c.width
    };
    for (let week in gitcalendar.data) {
      weekdata = gitcalendar.data[week];
      for (let day in weekdata) {
        let dataitem = {
          date: "",
          count: "",
          x: 0,
          y: 0
        };
        gitcalendar.positionplusdata.push(dataitem);
        ctx.fillStyle = gitcalendar.thiscolor(weekdata[day].count);
        setposition.y = Math.round(setposition.y * 100) / 100;
        dataitem.date = weekdata[day].date;
        dataitem.count = weekdata[day].count;
        dataitem.x = setposition.x;
        dataitem.y = setposition.y;
        ctx.fillRect(setposition.x, setposition.y, lineminwitdh, lineminwitdh);
        setposition.y = setposition.y + linemaxwitdh
      };
      setposition.y = 0.025 * c.width;
      setposition.x = setposition.x + linemaxwitdh
    };
    ctx.font = "600  Arial";
    ctx.fillStyle = '#aaa';
    ctx.fillText("日", 0, 1.9 * linemaxwitdh);
    ctx.fillText("二", 0, 3.9 * linemaxwitdh);
    ctx.fillText("四", 0, 5.9 * linemaxwitdh);
    ctx.fillText("六", 0, 7.9 * linemaxwitdh);
    let monthindexlist = c.width / 24;
    for (let index in gitcalendar.monthchange) {
      ctx.fillText(gitcalendar.monthchange[index], monthindexlist, 0.7 * linemaxwitdh);
      monthindexlist = monthindexlist + c.width / 12
    };
    cmessage.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
    };
    c.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
      getMousePos(c, event);
    };

    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left * (canvas.width / rect.width);
      var y = event.clientY - rect.top * (canvas.height / rect.height);
      //console.log("x:"+x+",y:"+y);
      for (let item of gitcalendar.positionplusdata) {
        let lenthx = x - item.x;
        let lenthy = y - item.y;
        //console.log(lenthx,lenthy);
        if (0 < lenthx && lenthx < lineminwitdh) {
          if (0 < lenthy && lenthy < lineminwitdh) {
            //console.log(item.date,item.count)
            document.querySelector('.angle-wrapper').style.display = 'block'
            gitcalendar.span1 = item.date;
            gitcalendar.span2 = item.count;
            gitcalendar.x = event.clientX - 100;
            gitcalendar.y = event.clientY - 60
          }
        }
        //if(0< x - item.x <lineminwitdh&&0< y - item.y <lineminwitdh){
        //console.log(item.count,item.date);
        //}
      }
    }
  }
}
//数据统计算法
function addlastmonth() {
  if (gitcalendar.thisdayindex === 0) {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweekcore(48);
    gitcalendar.thisweekdatacore += gitcalendar.firstdate[6].count;
    gitcalendar.amonthago = gitcalendar.firstdate[6].date
  } else {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweek2core();
    gitcalendar.amonthago = gitcalendar.first2date[gitcalendar.thisdayindex - 1].date
  }
};

function thisweek2core() {
  for (let i = gitcalendar.thisdayindex - 1; i < gitcalendar.first2date.length; i++) {
    gitcalendar.thisweekdatacore += gitcalendar.first2date[i].count
  }
};

function thisweekcore(index) {
  for (let item of gitcalendar.data[index]) {
    gitcalendar.thisweekdatacore += item.count
  }
};

function addlastweek() {
  for (let item of gitcalendar.lastweek) {
    gitcalendar.weekdatacore += item.count
  }
};

function addbeforeweek() {
  for (let i = gitcalendar.thisdayindex; i < gitcalendar.beforeweek.length; i++) {
    gitcalendar.weekdatacore += gitcalendar.beforeweek[i].count
  }
};

function addweek(data) {
  if (gitcalendar.thisdayindex === 6) {
    gitcalendar.aweekago = gitcalendar.lastweek[0].date;
    addlastweek()
  } else {
    lastweek = data.contributions[51];
    gitcalendar.aweekago = lastweek[gitcalendar.thisdayindex + 1].date;
    addlastweek();
    addbeforeweek()
  }
}

fetch(githubapiurl)
  .then(data => data.json())
  .then(data => {
    gitcalendar.data = data.contributions;
    gitcalendar.total = data.total;
    gitcalendar.first2date = gitcalendar.data[48];
    gitcalendar.firstdate = gitcalendar.data[47];
    gitcalendar.firstweek = data.contributions[0];
    gitcalendar.lastweek = data.contributions[52];
    gitcalendar.beforeweek = data.contributions[51];
    gitcalendar.thisdayindex = gitcalendar.lastweek.length - 1;
    gitcalendar.thisday = gitcalendar.lastweek[gitcalendar.thisdayindex].date;
    gitcalendar.oneyearbeforeday = gitcalendar.firstweek[0].date;
    gitcalendar.monthindex = gitcalendar.thisday.substring(5, 7) * 1;
    gitcalendar.montharrbefore = gitcalendar.month.splice(gitcalendar.monthindex, 12 - gitcalendar.monthindex);
    gitcalendar.monthchange = gitcalendar.montharrbefore.concat(gitcalendar.month);
    addweek(data);
    addlastmonth();
    responsiveChart();
  })
  .catch(function(error) {
    console.log(error);
  });

//手机版更换为svg绘制
if (document.getElementById("gitcalendarcanvasbox").offsetWidth < 500) {
  gitcalendar.simplemode = false
}

//当改变窗口大小时重新绘制canvas
window.onresize = function() {
  if (gitcalendar.simplemode) responsiveChart()
}

//解决滚动滑轮时出现的标签显示
window.onscroll = function() {
  if (document.querySelector('.angle-wrapper')) {
    document.querySelector('.angle-wrapper').style.display = 'none'
  }
};</script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body></html>